package com.qzsoft.system.modules.permission.roleclass.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qzsoft.jeemis.common.exception.RenException;
import com.qzsoft.jeemis.common.utils.ConvertDictUtils;
import com.qzsoft.jeemis.common.utils.ConvertUtils;
import com.qzsoft.jeemis.common.utils.TreeUtils;
import com.qzsoft.system.common.PinYinUtils;

import com.qzsoft.system.modules.permission.role.dao.SysRoleMapper;
import com.qzsoft.system.modules.permission.role.dto.SysRoleDTO;
import com.qzsoft.system.modules.permission.roleclass.dao.SysRoleClassDao;
import com.qzsoft.system.modules.permission.roleclass.dto.SysRoleClassDTO;
import com.qzsoft.system.modules.permission.roleclass.dto.SysRoleClassTreeDTO;
import com.qzsoft.system.modules.permission.roleclass.entity.SysRoleClassEntity;
import com.qzsoft.system.modules.permission.roleclass.service.SysRoleClassService;
import com.qzsoft.system.repository.sys.dao.SysRoleDao;
import com.qzsoft.system.repository.sys.entity.SysRoleEntity;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限角色分组表(权限角色)(SysRoleGroup)表服务实现类
 *
 * @author zt
 * @since 2020-09-22 14:24:44
 */
@Service("sysRoleGroupService")
@Log4j2
public class SysRoleClassServiceImpl implements SysRoleClassService {

    @Autowired
    private SysRoleClassDao sysRoleClassDao;

    @Autowired
    private SysRoleDao sysRoleDao;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 分组树检索
     *
     * @return
     */
    @Override
    public List<SysRoleClassTreeDTO> treeFolder() {
        QueryWrapper<SysRoleClassEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("has_delete", 0);
        queryWrapper.eq("has_group", 1).orderByAsc("order_id");
        List<SysRoleClassEntity> roleBusinessEntityList = sysRoleClassDao.selectList(queryWrapper);
        List<SysRoleClassTreeDTO> roleBusinessGroupDTOList = ConvertUtils
                .sourceToTarget(roleBusinessEntityList, SysRoleClassTreeDTO.class);
        roleBusinessGroupDTOList = TreeUtils.build(roleBusinessGroupDTOList, '0');
        return roleBusinessGroupDTOList;
    }

    /**
     * 返回分组和角色树
     *
     * @return
     */
    @Override
    public List<SysRoleClassTreeDTO> treeRoleList() {
        List<SysRoleClassTreeDTO> SysRoleClassTreeDTOList = sysRoleDao.selectGroupRoleList();
        SysRoleClassTreeDTOList = TreeUtils.build(SysRoleClassTreeDTOList, '0');
        return SysRoleClassTreeDTOList;
    }

    @Override
    public List<SysRoleClassTreeDTO> getTreeRoleList(List<String> deptids, List<String> groupids) {
        List<SysRoleClassTreeDTO> list = new ArrayList<>();
        List<SysRoleClassTreeDTO> SysRoleClassTreeDTOList = sysRoleDao.selectGroupRoleList();
        SysRoleClassTreeDTOList = TreeUtils.build(SysRoleClassTreeDTOList, '0');
        SysRoleClassTreeDTO commonUserRoles = new SysRoleClassTreeDTO();
        commonUserRoles.setName("通用角色");
        commonUserRoles.setHasGroup(true);
        commonUserRoles.setChildren(SysRoleClassTreeDTOList);
        list.add(commonUserRoles);

        //组织角色
        SysRoleClassTreeDTO tree2 = new SysRoleClassTreeDTO();
        tree2.setName("机构角色");
        tree2.setHasGroup(true);
        tree2.setId("dept");
        List<SysRoleClassTreeDTO> deptRoleList = queryDefaultRolesBydeptIds(deptids);
        // deptChildrenList = TreeUtils.build(deptChildrenList, "dept");
        tree2.setChildren(deptRoleList);
        list.add(tree2);

        //用户组角色
        SysRoleClassTreeDTO tree3 = new SysRoleClassTreeDTO();
        List<SysRoleClassTreeDTO> userGroupRoleList = queryDefaultRolesByGroupIds(groupids);
        tree3.setName("用户组角色");
        tree3.setHasGroup(true);
        tree3.setChildren(userGroupRoleList);
        list.add(tree3);
        return list;
    }


    /**
     * 分组添加
     *
     * @param sysRoleClassEntity
     * @return
     */
    @Override
    public int save(SysRoleClassEntity sysRoleClassEntity) {
        // 当父节点为空的时候则为根节点（0）
        if (StringUtils.isBlank(sysRoleClassEntity.getPid())) {
            sysRoleClassEntity.setPid("0");
        }
        // 排序
        if (sysRoleClassEntity.getOrderId() == null) {
            // 获取最大排序
            Integer maxSort = sysRoleClassDao.selectMaxOrderIdByPId(sysRoleClassEntity.getPid());
            if (maxSort != null) {
                sysRoleClassEntity.setOrderId(maxSort + 1);
            } else {
                sysRoleClassEntity.setOrderId(0);
            }
        }
        //全拼、简拼设置
        sysRoleClassEntity.setPinyin(PinYinUtils.getFullPinYin(sysRoleClassEntity.getName()));
        sysRoleClassEntity.setSpell(PinYinUtils.getSpell(sysRoleClassEntity.getName()));
        // 数据插入
        int result = sysRoleClassDao.insert(sysRoleClassEntity);
        if (result <= 0) {
            throw new RenException("角色分组添加失败");
        }
        return result;
    }

    @Override
    public SysRoleClassEntity get(String id) {
        SysRoleClassEntity entity = sysRoleClassDao.selectById(id);
        // 如无需代码翻译请屏蔽这句话 提高速度
        entity = ConvertDictUtils.formatDicData(entity);
        return entity;
    }

    /**
     * 更新分组
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(SysRoleClassDTO dto) {
        // 根据ID获取分组信息
        SysRoleClassEntity entity = sysRoleClassDao.selectById(dto.getId());
        // 分组名称
        entity.setName(dto.getName());
        // 上级节点
        if (StringUtils.isNotBlank(dto.getPid())) {
            entity.setPid(dto.getPid());
        } else {
            entity.setPid("0");
        }
        // 简拼
        entity.setSpell(dto.getSpell());
        // 拼音
        entity.setPinyin(dto.getPinyin());
        // 备注
        entity.setRemark(dto.getRemark());
        // 排序
        if (dto.getOrderId() != null) {
            entity.setOrderId(dto.getOrderId());
        } else {
            // 获取最大排序
            Integer maxSort;
            if (StringUtils.isNotBlank(dto.getPid())) {
                maxSort = sysRoleClassDao.selectMaxOrderIdByPId(dto.getPid());
            } else {
                maxSort = sysRoleClassDao.selectMaxOrderId();
            }
            if (maxSort != null) {
                entity.setOrderId(maxSort + 1);
            } else {
                entity.setOrderId(0);
            }
        }
        //更新角色
        int result = sysRoleClassDao.updateById(entity);
        if (result <= 0) {
            throw new RenException("角色分组更新失败");
        }
        return result;
    }

    /**
     * 批量删除分组
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String[] ids) {
        // 判断分组下面是否有子分组
        QueryWrapper<SysRoleClassEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("has_delete", 0);
        queryWrapper.in("pid", ids);
        if (sysRoleClassDao.selectCount(queryWrapper) > 0) {
            throw (new RenException("请先删除下级分组"));
        }

        // 判断分组是否系统内置分组
        QueryWrapper<SysRoleClassEntity> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("id", ids).eq("has_system", 1);
        if (sysRoleClassDao.selectCount(queryWrapper2) > 0) {
            throw (new RenException("内置分组不允许删除"));
        }

        // 判断分组下面是否有角色
        QueryWrapper<SysRoleEntity> getRoleWrapper = new QueryWrapper<>();
        getRoleWrapper.eq("class_id", ids[0]);
        if (sysRoleMapper.selectCount(getRoleWrapper) > 0) {
            throw (new RenException("请删除组内角色后再重试"));
        }

        // 删除角色
        UpdateWrapper<SysRoleClassEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids).set("has_delete", "1");
        sysRoleClassDao.update(new SysRoleClassEntity(), updateWrapper);
    }

    @Override
    public SysRoleDTO getDeptDefaultRole(String deptId) {
        SysRoleDTO sysRoleV2DTO = sysRoleDao.getDeptDefaultRole(deptId);
        return sysRoleV2DTO;
    }


    public List<SysRoleClassTreeDTO> queryDefaultRolesBydeptIds(List<String> deptids) {

        List<SysRoleClassTreeDTO> deptChildrenList = new ArrayList<>();
        for (int i = 0; i < deptids.size(); i++) {
            SysRoleClassTreeDTO deptDefaultRole = sysRoleClassDao.queryDefaultRoleBydeptId(deptids.get(i));
            if (deptDefaultRole != null && !deptDefaultRole.equals("")) {
                deptDefaultRole.setHasGroup(false);
                deptDefaultRole.setType("1");
                deptChildrenList.add(deptDefaultRole);
            }


        }

        return deptChildrenList;
    }

    public List<SysRoleClassTreeDTO> queryDefaultRolesByGroupIds(List<String> groupids) {
        List<SysRoleClassTreeDTO> groupChildrenList = new ArrayList<>();
        for (int i = 0; i < groupids.size(); i++) {
            List<SysRoleClassTreeDTO> groupDefaultRoleList = sysRoleClassDao.queryDefaultRoleByGroup(groupids.get(i));
            for (int n = 0; n < groupDefaultRoleList.size(); n++) {
                SysRoleClassTreeDTO groupDefaultRole = groupDefaultRoleList.get(n);
                if (groupDefaultRole != null && !groupDefaultRole.equals("")) {
                    groupDefaultRole.setHasGroup(false);
                    groupDefaultRole.setType("2");
                    groupChildrenList.add(groupDefaultRole);
                }

            }


        }

        return groupChildrenList;
    }

}